/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: Shentong
 * @Date: 2021-04-09 12:34:34
 * @LastEditors: shentong
 * @LastEditTime: 2022-02-25 21:11:04
 */
// eslint-disable-next-line @typescript-eslint/no-use-before-define
import React, { useEffect, useState, useCallback, useMemo } from "react";
import Taro, { useRouter, useDidShow, useDidHide } from '@tarojs/taro'

import { connect } from 'react-redux'

 import { View } from "@tarojs/components";
 import { AtIcon, AtAvatar, AtFloatLayout } from 'taro-ui'
 import { getStoregeByKey, showToast } from '@/utils/index'

import { gettlement, submitOrder, shopOrderDate, wxPay } from '@/api/order'
import { getAddressPage } from '@/api/user'

import SelectTimeDrawer from './components/selectTime/index'

 import styles from './index.module.scss'

 const SubmitOrderPage = (props) => {
  const {  curAddress, curConponId, curRedPackId, dispatch } = props

   // 商铺名称
   const [shopName, setShopName] = useState('')
   // 选择的商品数组
   const [goodsList, setGoodsList] = useState([])
   // 优惠金额
   const [couponAmount ,setCouponAmount] = useState(0)
   // 可用优惠券
   const [availableCoupon, setAvailableCoupon] = useState(0.00)
   // 可用红包数量
   const [availableRedPacketCount, setAvailableRedPacketCount] = useState(0.00)
   // 店铺活动
   const [activitys, setActivitys] = useState([])
   // 餐盒价格
   const [lunchboxPrice, setLunchboxPrice] = useState(0.00)
   // 餐盒总数
   const [lunchboxTotalNum, setLunchboxTotalNum] = useState(0.00)
   // 优惠价格
   const [preferential, setPreferential] = useState(0.00)
   // 配送费用
   const [deliveryCost, setDeliveryCost] = useState(0.00)
   // 使用红包金额
   const [redPacketAmount, setRedPacketAmount] = useState(0.00)
   // 红包列表
   const [redPackets, setRedPackets] = useState([])
   // 优惠券列表
   const [userCoupon, setUserCoupon] = useState([])
   // 固定取餐时间
   const [takeMealsTimeVo, setTakeMealsTimeVo] = useState(null)
   // 总价格
   const [totalPrice, setTotalPrice] = useState(0.00)
   // 备注
   const [remark, setRemark] = useState('')
   // 提交订单loading
   const [submitLoading, setSubmitLoading] = useState(false)
   // 选择送餐时间抽屉
   const [showDrawer, setShowDrawer] = useState(false)
   // 送餐时间列表
   const [shopDateList, setShopDateList] = useState([])
   // 页面只显示 '12:00' 这种类型的时间 （非用来提交）
   const [onlyTime, setOnlyTime] = useState('')
   // 选择的送出时间（提交时接口所需要的数据）
   const [currentDate, setCurrentDate] = useState<string>('')
   const [openTimeTool, setOpenTimeTool] = useState<boolean>(false)
   // 购物车信息
   const [curCartInfo, setCurCartInfo] = useState(null)
   const [defaultAddress, setDefaultAddress] = useState({
    address: '',
    cellPhone: '',
    userName: '',
    gender: 1,
    addressId: ''
   })

   const routerParams = useRouter().params;

   // 判断是否为 立即送出
   const judgeIsSendNow = useMemo(()=> {
    // 取 shopDateList 中第一条数据
    if (shopDateList.length) {
      const [{date = '', orderTimes = []} = {}] = shopDateList
      const [{ time }] = orderTimes
      if (`${date} ${time}` === currentDate) return true
    }

    return false
   }, [currentDate, shopDateList])

   // 获取默认收货地址
   const getAddressInfo = useCallback(async () => {
    try {
      const addressInfo = await getAddressPage({ pageSize: 1, pageNo: 1 })
      const { data: { records = [] } = {} } = addressInfo

      let _address = {}

      if (records && records.length){
        const [first] = records
        _address =  Object.assign(first, {
          addressId: first.addressSId
        })
        if (curAddress.address) {
          _address = { ...curAddress }
        }
      }
      console.log('_address', _address)
      setDefaultAddress({..._address})
      return _address
    } catch (error) {}
   },[curAddress])

   interface IWxPayParams {
    timestamp: string; // 时间戳，从 1970 年 1 月 1 日 00:00:00 至今的秒数，即当前的时间
    noncestr: string; // 随机字符串，长度为32个字符以下
    package: string; // 统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=***
    signType?: string; // 签名算法，应与后台下单时的值一致
    sign: string; // 签名，具体见微信支付文档
    t: string;
    success?: Function;
    fail?: Function;
    complete?: Function;
   }

  const doWxPay = (params: IWxPayParams) => {
    const reqParams = {
      timeStamp: params.t,
      nonceStr: params.noncestr,
      package: params.package,
      signType: 'MD5',
      paySign: params.sign,
      success: function (res) {
        console.log('微信支付成功', res)
        params.success()
       },
      fail: function () {
        params.fail()
        // showToast('微信支付失败，请重试！')
      },
      complete: function() {
        params.complete()
      }
    }
    console.log('支付参数', reqParams)

    Taro.requestPayment(reqParams)
  }

  // 判断本地是否缓存有商品详情页数据
  const judgeCartInfo = useCallback(async () => {
    // 获取用户信息
    const cartInfo = await getStoregeByKey('cartInfo')

    return cartInfo

  }, [])

   // 获取订单详情
   const getetail = useCallback(async () => {
    const cartInfo  = await judgeCartInfo()
    let theAddress = {}

    const newCartInfo = Object.assign(cartInfo, {
      userCouponId: curConponId.couponId,
      userRedPacketId: curRedPackId.redPackId,
    })

    if (newCartInfo.deliveryType !== 3) {
      theAddress  = await getAddressInfo()
    }

    if (!cartInfo) {
      showToast('商品信息获取失败，请从新下单！', {
        complete: () => Taro.navigateBack()
      })
      return
    }

    newCartInfo.userAddressId = theAddress.addressId || defaultAddress.addressId

    setCurCartInfo(newCartInfo)

    Taro.showLoading({ title: "加载中...", mask: true })
    gettlement(newCartInfo).then((res) => {
      const { data: {
        items = [],
        shopName:shop = '',
        deliveryCost: deliveryPrice = 0.00,
        totalPrice: allPrice = 0.00,
        takeMealsTimeVo:mealsTime = null,
        userCoupon: userCouponList = [],
        redPackets: redPackList = [],
        activitys: activity = [],
        redPacketAmount: useRedPackPrice = 0.00,
        preferential: prefer = 0.00,
        lunchboxPrice: boxPrice = 0.00,
        lunchboxTotalNum: boxNum = 0,
        availableCoupon: copons = 0.00,
        availableRedPacketCount: redPacks = 0,
        couponAmount: _couponAmount = 0
      } = {} } = res || {}

      setAvailableCoupon(copons)
      setShopName(shop)
      setAvailableRedPacketCount(redPacks)
      setGoodsList([...items])
      setCouponAmount(_couponAmount)
      setActivitys(activity)
      setLunchboxPrice(boxPrice)
      setLunchboxTotalNum(boxNum)
      setPreferential(prefer)
      setRedPacketAmount(useRedPackPrice)
      setRedPackets(redPackList)
      setUserCoupon(userCouponList)
      setTakeMealsTimeVo(mealsTime)
      setTotalPrice(allPrice)
      setDeliveryCost(deliveryPrice)

      Taro.hideLoading();

      dispatch({ type: 'ADDCOUPONLIST', payload: userCouponList})
    }).catch(err => {
      const { code, errMsg = '' } = err
      if (code === '00002-00022' && errMsg === '红包已过期') {
        dispatch({ type: 'DEL_REDPACK_ID'})
      }
    })

   }, [judgeCartInfo, curConponId.couponId, curRedPackId.redPackId, defaultAddress.addressId, getAddressInfo, dispatch])

   // 获取 配送时间信息
   const shopDate = useCallback(() => {
    const { addressId: userAddressId } = defaultAddress
    const params = {
     userAddressId,
     shopId: routerParams.shopId
    }
    shopOrderDate(params).then(res => {
      const list = res.data || []
      setShopDateList(list)
      if(list.length) {
        const [{ date = '', orderTimes = [] }] = list
        const [{ time }] = orderTimes
        setOnlyTime(time)
        setCurrentDate(`${date} ${time}`)
      }
   })
  },[defaultAddress, routerParams.shopId])
   // 提交订单按钮
   const submitOrderHandle = async () => {
    setSubmitLoading(true)
    Taro.showLoading({ title: "加载中...", mask: true })

    try {
      const params = Object.assign({}, curCartInfo, {
        actualPayment: totalPrice,
        deliveryTime: currentDate,
        orderType: judgeIsSendNow ? 0 : 1, // 订单类型,  0:立即送达;   1:预订单
        remark,
        userAddressId: defaultAddress.addressId,
        userCouponId: curConponId?.couponId || '', // 当前选中的优惠券Id（如果有优惠券
        userRedPacketId: curRedPackId?.redPackId || '' // 当前选中的红包id（如果有红包）
      })
      const { data } = await submitOrder(params)

      if (data) {
        const { data: toPayData } = await payOrder(data)
        Taro.hideLoading()

        if (toPayData) {
          doWxPay({
            ...toPayData,
            success: () => {
              showToast('支付成功~', {
                complete: () => {
                  Taro.switchTab({ url: '/pages/order/index'})
                }
              })
            },
            fail: () => showToast('支付失败，请重新提交订单~'),
            complete: () => setSubmitLoading(false)
          })
        }
      }

    } catch (error) {
      if(error.code === '00002-00024') {
        setTimeout(() => {
          Taro.navigateTo({
            url: `/pages/myAddress/index?from=submitOrder`
          })
        }, 2000)
      }
      setSubmitLoading(false)
    }
   }

   /**
    * @description 支付订单
    * @param bizType: 0:外卖订单  1:抽奖订单(默认外卖订单) 默认0
    */
   const payOrder = (orderNumber, bizType = 0) => {
     if (!orderNumber) return
     const params = { orderNumber, bizType }
     return wxPay(params)
   }

   const selectAddress = () => {
     Taro.navigateTo({
       url: `/pages/myAddress/index?from=submitOrder`
     })
   }

   const onInput = (e) => {
   }
   const timeConfirm = (e) => {
    setCurrentDate(e.detail)
    setOpenTimeTool(false)
   }

   // 选择优惠券按钮
   const useCoupon = () => {
     if (!availableCoupon) {
      return showToast('暂无可用的优惠券~')
     }
     Taro.navigateTo({
      url: '/pages/coupon/index?fromPage=submitOrder'
     })
   }

   // 选择红包按钮
   const useRedPack = () => {
    if (!availableRedPacketCount) {
     return showToast('暂无可用的红包~')
    }
    Taro.navigateTo({
     url: '/pages/redPacket/index?fromPage=submitOrder'
    })
  }

   const drawerCloseHandle = (yearStr, timeStr) => {
     setShowDrawer(false)
     if (yearStr && timeStr) {
      setOnlyTime(timeStr)
      setCurrentDate(`${yearStr} ${timeStr}`)
     }
   }

   useEffect(()=> {
    console.log('-----', curCartInfo)
    //  if (curCartInfo && curCartInfo.deliveryType !== 3) shopDate()
      if (curCartInfo  && curCartInfo.deliveryType !== undefined) shopDate()

   },[curCartInfo, shopDate])

   useDidShow(() => {
    getetail()
   })

   return (
     <View className={styles.submitOrder}>
       {
         curCartInfo && curCartInfo.deliveryType === 1 ? (
           <React.Fragment>
             {/* 收获地址 */}
             <View className={styles.header} onClick={selectAddress}>
                {
                  defaultAddress.address ? (
                    <View className={styles.addressInfo}>
                      <View className={styles.address}>{defaultAddress.address}</View>
                      <View className={styles.namePhone}>
                        <View>{defaultAddress.userName}</View>
                        <View className={styles.gender}>{Number(defaultAddress.gender) === 0 ? '先生' : '女士'}</View>
                        <View>{defaultAddress.cellPhone}</View>
                      </View>
                    </View>
                  ) : <View className={styles.selectAddressBtn}>选择收货地址</View>
                }
                <View className={styles.rightArrow}>
                  <AtIcon value='chevron-right' size='24' color='#ccc'></AtIcon>
                </View>
              </View>
           </React.Fragment>

         ) : null
       }
       {/* 送出时间 */}
       <View className={styles.sendRightNow} onClick={() => setShowDrawer(true)}>
          {
            judgeIsSendNow ?
            curCartInfo && curCartInfo.deliveryType === 1 ?
              <View className={styles.title}>立即送出</View> : <View className={styles.title}>取餐</View>
            : curCartInfo && curCartInfo.deliveryType === 1 ?
              <View className={styles.title}>指定送出</View> :
              <View className={styles.title}>指定取餐</View>
          }
          <View className={styles.selectTime}>
          {
            judgeIsSendNow ? <View className={styles.time}>大约{onlyTime}</View> : <View className={styles.time}>大约{currentDate}</View>
          }
            <AtIcon value='chevron-right' size='24' color='#ccc'></AtIcon>
          </View>
        </View>
        <View className={styles.prodInfo}>
          <View className={styles.shopName}>{shopName}</View>
          {
            goodsList.map((item, index) => {
              return (
                <View className={styles.goodItem} key={index}>
                  <View className={styles.goodInfo}>
                    <AtAvatar image={item.goodsImagePath} className={styles.headerImg} size='normal'></AtAvatar>
                    <View className={styles.titleDesc}>
                      <View className={styles.tit}>{item.goodsName}</View>
                      <View className={styles.specAndpropertys}>
                        {
                          item.propertys && item.propertys.map((proterty, pIndex) => {
                            return <View className={styles.propertys} key={pIndex}>{proterty.propertyValue}</View>
                          })
                        }
                        <View className={styles.desc}>{item.goodsSpecName}</View>
                      </View>
                    </View>
                  </View>
                  <View className={styles.countMouney}>
                    <View className={styles.count}>x{item.goodsNum}</View>
                    <View className={styles.money}>￥{item.goodsPrice}</View>
                  </View>
                </View>
              )
            })
          }
        </View>
        <View className={styles.atList}>
          {
            activitys.map((active, index) => {
              return (
                <View className={styles.atItem} key={index}>
                  <View className={styles.label}>
                    {/* <Image src={} className={styles.labelIcon}></Image> */}
                    {
                      active.activityType == 1 ? <View className={styles.first}>首</View> : <View className={styles.cut}>减</View>
                    }
                    <View className={styles.labelName}>{active.activityName}</View>
                  </View>
                  <View className={styles.detail}>
                    <View className={styles.dName}>-￥{active.activityPrice}</View>
                  </View>
                </View>
              )
            })
          }
          <View className={styles.atItem} onClick={useCoupon}>
            <View className={styles.label}>
              <View className={styles.labelName}>优惠券</View>
            </View>
            <View className={styles.detail}>
              { couponAmount ?  <View className={styles.dName}>-￥{couponAmount}.0</View> : <View className={styles.dName}>{availableCoupon}张可用</View> }
              <AtIcon value='chevron-right' size='20' color='#ccc'></AtIcon>
            </View>
          </View>
          <View className={`${styles.atItem} ${styles.noBorder}`} onClick={useRedPack}>
            <View className={styles.label}>
              <View className={styles.labelName}>红包</View>
            </View>
            <View className={styles.detail}>
              { redPacketAmount ?  <View className={styles.dName}>-￥{redPacketAmount}.0</View> : <View className={styles.dName}>{availableRedPacketCount}张可用</View> }

              <AtIcon value='chevron-right' size='20' color='#ccc'></AtIcon>
            </View>
          </View>
          <View className={styles.atItem}>
            <View className={styles.label}>
              <View className={styles.labelName}>包装数量x{lunchboxTotalNum}</View>
            </View>
            <View className={styles.detail}>
              <View className={styles.dName}>
                <View className={styles.desc}>包装费用</View>
                ￥{lunchboxPrice}
              </View>
            </View>
          </View>
          <View className={styles.atItem}>
            <View className={styles.label}>
              <View className={styles.labelName}>配送费用</View>
            </View>
            <View className={styles.detail}>
              <View className={styles.dName}>￥{deliveryCost}</View>
            </View>
          </View>
          <van-cell-group>
            <van-field
              value={remark}
              type='textarea'
              placeholder='请填写备注'
              titleWidth='30px'
              autosize
              onChange={(e) => setRemark(e.detail)}
              customStyle='color: #000;padding-left:0;'
              show-confirm-bar
              labelClass={styles.remarkLabelClass}
            >
              <slot name='label' >备注</slot>
            </van-field>
          </van-cell-group>
        </View>
        <View className={styles.allCount}>
          <View className={styles.label}>已优惠</View>
          <View className={styles.money}>￥{preferential}</View>
          <View className={styles.label}>总价格</View>
          <View className={styles.allMoney}>￥{totalPrice}</View>
        </View>
          {/* <Form onSubmit={submitForm} reportSubmit>
              <Button formType="submit">提交订单</Button>
          </Form> */}
        <View className={styles.operateBtn}>
            <van-submit-bar
              loading={submitLoading}
              price={totalPrice * 100}
              buttonText='提交订单'
              button-type='submit'
              onSubmit={submitOrderHandle}
            />
        </View>
        <AtFloatLayout
          className={styles.activityList}
          isOpened={openTimeTool}
          onClose={() => setOpenTimeTool(false)}
        >
          {/* <View className={styles.timeToolTitle}>指定时间</View> */}
          <View className={styles.timeToolBox}>
            <van-datetime-picker
              title='指定时间'
              type='time'
              value={currentDate}
              min-hour={10}
              max-hour={20}
              onInput={onInput}
              onConfirm={timeConfirm}
              onCancel={() => setOpenTimeTool(false)}
            />
          </View>
      </AtFloatLayout>

      {/* 选择时间抽屉 */}
      <SelectTimeDrawer
        timeList={shopDateList}
        showDrawer={showDrawer}
        drawerClose={drawerCloseHandle}
      />
     </View>
   );
 }

 export default connect(({ curAddress, curConponId, curRedPackId }) => ({
  curAddress,
  curConponId,
  curRedPackId
}), dispatch => ({
  dispatch
}))(SubmitOrderPage)

